<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="资讯分类" prop="categoryId">
        <el-input
          v-model="selectedCategoryName"
          placeholder="请选择资讯分类"
          clearable
          readonly
          @clear="handleClearCategory"
          class="!w-240px"
        >
          <template #suffix>
            <Icon
              icon="ep:search"
              class="cursor-pointer hover:text-primary"
              @click="openCategoryDialog"
            />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="资讯标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入资讯标题"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          class="!w-240px"
        >
          <el-option label="停用" :value="0" />
          <el-option label="开启" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['system:consult-info:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['system:consult-info:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
            type="danger"
            plain
            :disabled="isEmpty(checkedIds)"
            @click="handleDeleteBatch"
            v-hasPermi="['system:consult-info:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
    >
    <el-table-column type="selection" width="55" />
      <el-table-column label="资讯ID" align="center" prop="id" />
      <!-- <el-table-column label="分类ID" align="center" prop="categoryId" /> -->
      <el-table-column label="分类" align="center" prop="categoryName" />
      <el-table-column label="封面图片" align="center" width="100px">
        <template #default="scope">
          <el-image
            v-if="scope.row.coverImage"
            :src="scope.row.coverImage"
            :preview-src-list="[scope.row.coverImage]"
            fit="cover"
            class="table-cover-image"
            :preview-teleported="true"
          >
            <template #error>
              <div class="image-slot">
                <Icon icon="ep:picture" :size="30" />
              </div>
            </template>
          </el-image>
          <span v-else class="text-gray-400">无</span>
        </template>
      </el-table-column>
      <el-table-column label="资讯标题" align="center" prop="title" />
      <el-table-column label="资讯详情" align="center" width="120px">
        <template #default="scope">
          <el-button
            v-if="scope.row.content"
            link
            type="primary"
            @click="handleViewContent(scope.row.content)"
          >
            查看详情
          </el-button>
          <span v-else class="text-gray-400">无</span>
        </template>
      </el-table-column>
      <el-table-column label="图片文件" align="center" width="120px">
        <template #default="scope">
          <el-button
            v-if="scope.row.files"
            link
            type="primary"
            @click="handleViewImages(scope.row.files)"
          >
            查看图片
          </el-button>
          <span v-else class="text-gray-400">未上传</span>
        </template>
      </el-table-column>
      <el-table-column label="标签" align="center" prop="tags" />
      <!-- <el-table-column label="摘要" align="center" prop="summary" /> -->
      <el-table-column label="状态" align="center" width="100px">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
            {{ scope.row.status === 1 ? '开启' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column
        label="发布时间"
        align="center"
        prop="publishTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <!-- <el-table-column label="来源" align="center" prop="source" /> -->
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['system:consult-info:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['system:consult-info:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ConsultInfoForm ref="formRef" @success="getList" />

  <!-- 分类选择弹窗 -->
  <ConsultCategorySelectDialog ref="categoryDialogRef" @confirm="handleCategoryConfirm" />

  <!-- 资讯详情弹窗 -->
  <Dialog v-model="contentDialogVisible" title="资讯详情" width="900px">
    <div class="content-viewer" v-html="currentContent"></div>
  </Dialog>

  <!-- 图片预览弹窗 -->
  <Dialog v-model="imageDialogVisible" title="图片文件列表" width="800px">
    <div class="image-list">
      <div v-for="(image, index) in imageList" :key="index" class="image-item">
        <div class="image-info">
          <span class="image-index">{{ index + 1 }}.</span>
          <el-image
            :src="image"
            :preview-src-list="imageList"
            :initial-index="index"
            fit="cover"
            class="image-preview"
            :preview-teleported="true"
          >
            <template #error>
              <div class="image-error">
                <Icon icon="ep:picture" :size="40" />
                <div>加载失败</div>
              </div>
            </template>
          </el-image>
          <span class="image-name">{{ getImageName(image) }}</span>
        </div>
        <div class="image-actions">
          <el-button link type="primary" @click="handlePreviewImage(index)">
            <Icon icon="ep:zoom-in" class="mr-5px" /> 预览
          </el-button>
          <el-button link type="success" @click="handleDownloadImage(image)">
            <Icon icon="ep:download" class="mr-5px" /> 下载
          </el-button>
        </div>
      </div>
    </div>
    <div v-if="imageList.length === 0" class="empty-state">
      <Icon icon="ep:picture" :size="60" />
      <p>暂无图片</p>
    </div>
  </Dialog>
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { ConsultInfoApi, ConsultInfoVO } from '@/api/system/consultinfo'
import ConsultInfoForm from './ConsultInfoForm.vue'
import ConsultCategorySelectDialog from './ConsultCategorySelectDialog.vue'
import type { consultCategoryVO } from '@/api/system/consultCategory'

/** 资讯信息 列表 */
defineOptions({ name: 'ConsultInfo' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<ConsultInfoVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  categoryId: undefined as number | undefined,
  title: undefined,
  status: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const categoryDialogRef = ref() // 分类选择弹窗
const selectedCategoryName = ref('') // 选中的分类名称

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ConsultInfoApi.getConsultInfoPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  selectedCategoryName.value = '' // 清空分类名称
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ConsultInfoApi.deleteConsultInfo(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除资讯信息 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await ConsultInfoApi.deleteConsultInfoList(checkedIds.value);
    checkedIds.value = [];
    message.success(t('common.delSuccess'))
    await getList();
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: ConsultInfoVO[]) => {
  checkedIds.value = records.map((item) => item.id);
}

/** 打开分类选择弹窗 */
const openCategoryDialog = () => {
  categoryDialogRef.value?.open()
}

/** 分类选择确认 */
const handleCategoryConfirm = (category: consultCategoryVO) => {
  queryParams.categoryId = category.id
  selectedCategoryName.value = category.name
}

/** 清空分类选择 */
const handleClearCategory = () => {
  queryParams.categoryId = undefined
  selectedCategoryName.value = ''
}

/** 资讯详情查看 */
const contentDialogVisible = ref(false)
const currentContent = ref('')

/** 查看资讯详情 */
const handleViewContent = (content: string) => {
  if (!content) return
  currentContent.value = content
  contentDialogVisible.value = true
}

/** 图片预览相关 */
const imageDialogVisible = ref(false)
const imageList = ref<string[]>([])

/** 查看图片 */
const handleViewImages = (files: string) => {
  if (!files) return
  
  // 文件URL可能是逗号分隔的多个文件
  imageList.value = files.split(',').filter(Boolean).map(url => url.trim())
  imageDialogVisible.value = true
}

/** 获取图片名称 */
const getImageName = (url: string) => {
  if (!url) return ''
  const fileName = url.substring(url.lastIndexOf('/') + 1)
  return decodeURIComponent(fileName)
}

/** 预览图片 */
const handlePreviewImage = (index: number) => {
  // el-image 的预览功能会自动触发
  const imageElements = document.querySelectorAll('.image-preview')
  if (imageElements[index]) {
    (imageElements[index] as HTMLElement).click()
  }
}

/** 下载图片 */
const handleDownloadImage = (url: string) => {
  if (!url) return
  
  // 创建一个临时的a标签来触发下载
  const link = document.createElement('a')
  link.href = url
  link.download = getImageName(url)
  link.target = '_blank'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  
  message.success('开始下载图片')
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ConsultInfoApi.exportConsultInfo(queryParams)
    download.excel(data, '资讯信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss">
// 资讯详情查看器样式
.content-viewer {
  max-height: 600px;
  overflow-y: auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  line-height: 1.8;
  color: #303133;
  
  // 富文本内容样式
  :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
    margin: 16px 0 12px;
    font-weight: 600;
    line-height: 1.5;
    color: #303133;
  }
  
  :deep(h1) {
    font-size: 28px;
  }
  
  :deep(h2) {
    font-size: 24px;
  }
  
  :deep(h3) {
    font-size: 20px;
  }
  
  :deep(h4) {
    font-size: 18px;
  }
  
  :deep(p) {
    margin: 12px 0;
    font-size: 14px;
    line-height: 1.8;
  }
  
  :deep(img) {
    max-width: 100%;
    height: auto;
    border-radius: 4px;
    margin: 12px 0;
    display: block;
  }
  
  :deep(ul), :deep(ol) {
    padding-left: 24px;
    margin: 12px 0;
  }
  
  :deep(li) {
    margin: 6px 0;
    line-height: 1.8;
  }
  
  :deep(blockquote) {
    margin: 12px 0;
    padding: 12px 16px;
    background-color: #f5f7fa;
    border-left: 4px solid #409eff;
    color: #606266;
  }
  
  :deep(pre) {
    background-color: #f5f7fa;
    padding: 12px;
    border-radius: 4px;
    overflow-x: auto;
    margin: 12px 0;
  }
  
  :deep(code) {
    background-color: #f5f7fa;
    padding: 2px 6px;
    border-radius: 3px;
    font-family: 'Courier New', monospace;
    font-size: 13px;
  }
  
  :deep(table) {
    width: 100%;
    border-collapse: collapse;
    margin: 12px 0;
  }
  
  :deep(table th), :deep(table td) {
    border: 1px solid #dcdfe6;
    padding: 8px 12px;
    text-align: left;
  }
  
  :deep(table th) {
    background-color: #f5f7fa;
    font-weight: 600;
  }
  
  :deep(a) {
    color: #409eff;
    text-decoration: none;
    
    &:hover {
      text-decoration: underline;
    }
  }
  
  :deep(strong), :deep(b) {
    font-weight: 600;
  }
  
  :deep(em), :deep(i) {
    font-style: italic;
  }
  
  :deep(hr) {
    margin: 20px 0;
    border: none;
    border-top: 1px solid #dcdfe6;
  }
}

// 表格中的封面图片样式
.table-cover-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  cursor: pointer;
  border: 1px solid #dcdfe6;
  transition: all 0.3s;
  
  &:hover {
    border-color: #409eff;
    transform: scale(1.05);
  }
}

.image-slot {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  color: #909399;
}

.image-list {
  max-height: 500px;
  overflow-y: auto;
  
  .image-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px;
    margin-bottom: 10px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    transition: all 0.3s;
    
    &:hover {
      background-color: #f5f7fa;
      border-color: #409eff;
    }
    
    .image-info {
      display: flex;
      align-items: center;
      flex: 1;
      gap: 12px;
      
      .image-index {
        font-weight: 600;
        color: #606266;
        min-width: 25px;
      }
      
      .image-preview {
        width: 80px;
        height: 80px;
        border-radius: 4px;
        cursor: pointer;
        border: 1px solid #dcdfe6;
        
        &:hover {
          border-color: #409eff;
        }
      }
      
      .image-error {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
        background-color: #f5f7fa;
        color: #909399;
        font-size: 12px;
      }
      
      .image-name {
        flex: 1;
        color: #606266;
        word-break: break-all;
        font-size: 14px;
      }
    }
    
    .image-actions {
      display: flex;
      gap: 8px;
      margin-left: 12px;
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: #909399;
  
  p {
    margin-top: 12px;
    font-size: 14px;
  }
}
</style>